package cn.topevery.garden.wapi.controller;

import cn.topevery.garden.dal.logic.*;
import cn.topevery.garden.entity.impot.ScenicImportParam;
import cn.topevery.garden.entity.po.Scenic;
import cn.topevery.garden.entity.po.ScenicFile;
import cn.topevery.garden.entity.query.ScenicQuery;
import cn.topevery.garden.entity.vo.ScenicVO;
import cn.topevery.garden.wapi.utils.ExcelUtils;
import cn.topevery.garden.wapi.utils.StatusUtils;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.entity.DataPager;
import hw.topevery.framework.util.ExcelUtil;
import hw.topevery.framework.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  景点管理
 *
 * @author code-generate
 * @date 2021-08-06
 */
@Api(tags = "景点接口")
@RestController
@RequestMapping("/scenic")
public class ScenicController extends BaseController {


    @Autowired
    ScenicLogic scenicLogic;

    @Autowired
    ScenicFileLogic scenicFileLogic;

    @Autowired
    SectionLogic sectionLogic;

    @Autowired
    ParkLogic parkLogic;

    @Autowired
    ExtentLogic extentLogic;

    /**
     * 获取分页列表
     *
     * @param query
     * @return
     */
    @ApiOperation(value = "获取页列表")
    @PostMapping("/listPage")
    public JsonResult<DataPager<Scenic>> listPage(@RequestBody ScenicQuery query) {
        DataPager<Scenic> pageList = scenicLogic.listPage(query);
        for(Scenic scenic : pageList.records){
            // 获取附件
            List<ScenicFile> fileList = scenicFileLogic.getListByPid(scenic.getId());
            scenic.setFileList(fileList);
        }
        return JsonResult.ok(pageList);
    }

    @ApiOperation("新增/编辑 信息")
    @PostMapping("/saveOrUpdate")
    public JsonResult saveOrUpdate(@Valid @RequestBody Scenic dto) {
        Integer UserId=getUser().id;
        boolean isSave = scenicLogic.saveOrUpdate(UserId.toString(),dto);
        if(isSave) {
            // 保存附件
            scenicFileLogic.saveOrUpdate(UserId.toString(), dto.getId(), dto.getFileList());

            return JsonResult.ok(true);
        }else {
            return JsonResult.error("保存失败");
        }

    }


    @ApiOperation("根据自增ID批量删除")
    @GetMapping("/deleteBatchById")
    public JsonResult<Boolean> deleteBatchById(@RequestParam Integer[] ids) {
        scenicLogic.deleteBatchById(getUser().id.toString(),ids);
        return JsonResult.ok(true);
    }

    @ApiOperation("导出信息")
    @GetMapping("/export")
    public void export(ScenicQuery query, HttpServletResponse response) {
        List<Scenic> list = scenicLogic.listPage(query).records;
        ExcelUtil.exportExcel(list, "", "sheet1", Scenic.class, "", response);
    }

    /**
     * 描述 检查导入数据.
     *
     * @param file the file
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:59 Analysis excel data json result.
     */
    @PostMapping("/analysisExcel")
    public JsonResult AnalysisExcelData(@RequestParam("file") MultipartFile file) {
        boolean isPass = true;
        String msg = "";
        List<ScenicVO> persons = null;
        try {
            persons = ExcelUtils.importExcel(file, 0, 1, ScenicVO.class);
        } catch (Exception e) {
            msg = "解析发生错误，请按照模板格式填写数据！";
            return JsonResult.error(msg);
        }

        List<ScenicVO> newData = new ArrayList<>();
        for (ScenicVO p : persons) {
            String anaylsisRes = "";
            if (p.getSid() == 0 && p.getName() == null) {
                break;
            }
            boolean isExists1 = scenicLogic.isExit("c_code", p.getCode());
            if (isExists1) {
                anaylsisRes += "景点编码与现有重复；";
            }

            // 检查是否存在标段
            if(StringUtils.isNotEmpty(p.getSectionName())){
                Integer sectionId = sectionLogic.getSectionIdByName(p.getSectionName());
                if(sectionId == null){
                    anaylsisRes += "系统不存在名称为："+ p.getSectionName() +" 的标段，请确定标段名称是否正确；";
                }
                p.setSectionId(sectionId);
            }

            // 检查是否存在公园
            Integer parkId = null;
            if(StringUtils.isNotEmpty(p.getParkCode())){
                parkId = parkLogic.getParkIdByCodeAndName(p.getParkCode(), p.getParkName());
                if(parkId == null){
                    anaylsisRes += "系统不存在编号为："+ p.getParkCode() +" 的公园，请确定编号是否正确；";
                }
                p.setParkId(parkId);
            }

            // 检查是否存在片区
            if(StringUtils.isNotEmpty(p.getExtentName())){
                Integer extentId = extentLogic.getExtentIdByParkIdAndName(parkId, p.getExtentName());
                if(extentId == null){
                    anaylsisRes += "系统中编号为："+ p.getParkCode() +" 的公园不存在名称为："+ p.getExtentName() +" 的片区，请确定该片区是否正确；";
                }
                p.setExtentId(extentId);
            }

            if (anaylsisRes.length() > 0) {
                p.setPass(false);
                p.setAnalysisRes(anaylsisRes);
            } else {
                p.setPass(true);
                p.setAnalysisRes("验证通过");
            }
            newData.add(p);
        }
        isPass = !newData.stream().anyMatch(a -> a.isPass() == false);
        Map<String, Object> res = new HashMap<>();
        res.put("isPass", isPass);
        res.put("data", newData);
        return JsonResult.ok(res);
    }

    /**
     * 描述 导入数据.
     *
     * @param param the param
     * @return the json result
     * @author wenzhao.lin
     * @created 2021 -08-19 09:35:53 Import excel data json result.
     */
    @PostMapping("/importExcel")
    public JsonResult importExcelData(@RequestBody ScenicImportParam param) {

        SysUser user = getUser();
        if (param.getTableData() != null && param.getTableData().size() > 0) {

            for (ScenicVO p : param.getTableData()) {
                Scenic tmp = new Scenic();
                //Integer parkId = parkLogic.getParkIdByCodeAndName(p.getParkCode(), p.getParkName());

                tmp.setCode(p.getCode());
                tmp.setName(p.getName());
                //tmp.setSectionId(sectionLogic.getSectionIdByName(p.getSectionName()));
                tmp.setSectionId(p.getSectionId());
                tmp.setParkId(p.getParkId());
                //tmp.setExtentId(extentLogic.getExtentIdByParkIdAndName(parkId, p.getExtentName()));
                tmp.setExtentId(p.getExtentId());
                tmp.setAddress(p.getAddress());
                tmp.setLngBd09(p.getLngBd09());
                tmp.setLatBd09(p.getLatBd09());
                tmp.setStatus(StatusUtils.getOpenStatus(p.getStatus()));
                tmp.setDescs(p.getDesc());

                scenicLogic.saveOrUpdate(user.id.toString(),tmp);
            }
        } else {
            return JsonResult.error("导入数据列表不能为空");
        }
        return JsonResult.ok();
    }
}
